// import logo from './logo.svg';
import { useState, useRef, useEffect } from 'react';
import { Layout, message, Modal, Popover } from 'antd';

import 'antd/dist/reset.css';
import './App.css';

import Luckysheet from 'src/component/Luckysheet'
import ReportTree from 'src/component/ReportTree'
import RenderDialog from 'src/component/RenderDialog'
import SparkChannel, { EE } from 'src/ipc/sparkchannel'
import { ReportFile } from 'src/core/common'


const { Content, Sider } = Layout;

function App() {
  const [report, setReport] = useState(null);
  const [content, setContent] = useState(null);
  const [renderDialogOpen, setRenderDialogOpen] = useState(false);
  const [renderReport, setRenderReport] = useState(null); // 即将打开的报表
  const [renderContent, setRenderContent] = useState(null);
  const [signalDebug, setSignalDebug] = useState(null);
  const worksheet = useRef(null);

  useEffect(() => {
    if (process.env.NODE_ENV === 'development') {
      SparkChannel().then(channel => {
        const { signalDebug } = channel;
        setSignalDebug(signalDebug);
      });
    }
  }, []);

  const renderTemplate = (report, content, userValues) => {
    console.log('renderTemplate', report, content, userValues);
    setRenderDialogOpen(false);

    return new Promise((resolve) => {
      content = worksheet.current.renderTemplate(report, content, userValues, () => {
        resolve();
      });
      setReport(report);
      setContent(content);
    });
  };


  useEffect(() => {
    async function handler(request) {
      const newReport = request.report;
      console.log('auto export', report);

      const newContent = await ReportFile.readContent(newReport);
      const userValues = RenderDialog.defaultUserValues(newContent.config);
      await renderTemplate(newReport, newContent, userValues);
      worksheet.current.exportWorkbook();
    }
    EE.on('export_report_changed', handler);

    return function cleanup() {
      EE.removeListener('export_report_changed', handler);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    async function handler(newReport) {
      try {
        const newContent = await ReportFile.readContent(newReport);
        console.log('read report content', newContent);
        if (RenderDialog.isDialogEmpty(newContent.config)) {
          renderTemplate(newReport, newContent);
        } else {
          setRenderReport(newReport);
          setRenderContent(newContent);
          setRenderDialogOpen(true);
        }
      } catch (err) {
        console.log('open lxls fail', err);
        message.error('读取文件失败');
      }
    }
    EE.on('open-workbook', handler);

    // Specify how to clean up after this effect:
    return function cleanup() {
      EE.removeListener('open-workbook', handler);
    };
  }, []);

  return (
    <Layout>
      <Sider className='report-tree-wrapper'>
        <ReportTree />
      </Sider>
      <Content>
        <Luckysheet
          allowExport
          ref={worksheet}
          report={report}
          content={content} />
      </Content>

      {signalDebug}

      <RenderDialog
        report={renderReport}
        content={renderContent}
        open={renderDialogOpen}
        onCancel={() => setRenderDialogOpen(false)}
        onComplete={renderTemplate} />

      {/* Fix: 解决在QWebEngineView中Modal静态方法弹出框位置定位错误的问题 */}
      <Modal title="" open={false} />
      {/* Fix: 添加一个Popover，可以解决在QWebEngineView中Popover位置定位错误的问题 */}
      <Popover title="">
        <div />
      </Popover>
    </Layout>

    // <div className="App">
    //   <header className="App-header">
    //   </header>
    // </div>
  );
}

export default App;

// exportExcel({"directory_id": 1,"id": 1,"report_name": "output", "report_type": 1})
window.exportExcel = (report) => {
  if (!report) return false;

  const listeners = EE.listeners('export_report_changed');
  if (listeners.length === 0) {
    return false;
  } else {
    EE.emit('export_report_changed', { report });
    // listeners.forEach(fn => { fn({ report }); });
    return true;
  }
}